package com.yuga.controller
{
	import controllers.managers.LocationQueryManager;
	import controllers.managers.ScheduleManager;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.setTimeout;
	
	import mx.collections.ArrayList;
	import mx.logging.ILogger;
	
	import utils.LogUtil;

	//Added by kant
	//Reason : 查询队列，查询后将返回结果存入结果视图
	//Date : Nov 11, 2012 11:37:56 PM
	
	//用例:
//	var mgr:QueryQueenManager = new QueryQueenManager();
//	mgr.setLocList(TEST_LOC_LIST);
//	mgr.addEventListener(QueryQueenManager.QUEE_COMPLETE, function():void{
//		var address:String = mgr.getAddress("59.9370622147,136.410935563");
//		trace("输出:" + address);
//	});
//	mgr.start();
	
	public class QueryQueenManager extends EventDispatcher
	{
		public static var QUEE_COMPLETE : String = "QUEE_COMPLETE";
		public static var TASK_NAME : String = "QUEEN";
		public static var INTERVAL : int = 1000;
		
		public static var NAME : String = "QueryQueenManager";
		private var logger:ILogger =  LogUtil.getInst().getLogger( NAME );
		private var addressList:Array = new Array();
		private var scheduleMgr:ScheduleManager = null;
		private var timer:Timer = null;
		private var map:Object = [];
		public var queryLatlng:String = null;
		private var index:int = 0;
		
		public function QueryQueenManager()
		{
			scheduleMgr = new ScheduleManager();
			timer = scheduleMgr.createTimer(TASK_NAME, INTERVAL, onTimeHandler);
			
			initEvent();
		}
		
		private function initEvent():void
		{
			
		}
		
		public function start():void
		{
			scheduleMgr.startTask(TASK_NAME);
		}
		
		protected function onAddressRespHandler(evt:Event):void
		{
			var service:LocationQueryManager = LocationQueryManager(evt.currentTarget);
			setAddress(service.queryLatlng, service.formattedAddress);
		}
		
		public function getAddress(latlngStr:String):String
		{
			return String(map[latlngStr] );
		}
		
		private function setAddress(key:String, value:String):void
		{
			map[key] = value;
		}
		
		protected function onTimeHandler(evt:TimerEvent):void
		{
			query( addressList[index] );
			
			if( index == addressList.length-1)
			{
				logger.info("关闭调度器");
				scheduleMgr.stopTask(TASK_NAME);			
				dispatchEvent( new Event(QUEE_COMPLETE));
			}
			index ++;
		}
		
		public function query(latlngStr:String):void
		{
			var queryService : LocationQueryManager = new LocationQueryManager();
			queryService.query( latlngStr );
			queryService.addEventListener(LocationQueryManager.EVENT_UPDATE, onAddressRespHandler);
		}
			
		public function addLocation(latlng:Object):void
		{
			addressList.push( latlng );
		}	
		
		public function setLocList(list:Array):void
		{
			addressList = list;
		}
	}
}